/*
 * @Author: Leo.wang wanglizhigs@163.com
 * @Date: 2024-06-11 22:19:08
 * @LastEditors: Leo.wang wanglizhigs@163.com
 * @LastEditTime: 2024-06-16 21:29:21
 * @FilePath: /chat-ai-plus/src/pages/mobile/hooks.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { ref } from 'vue';
import { sendCode, modifyPhone } from '@/api/user.api';
import { omit, pick } from 'lodash-es';
import useUserStore from '@/store/modules/user';
import { useI18n } from 'vue-i18n';

export function useFormState() {
  const { t } = useI18n(); 
  const userStore = useUserStore();
  const countdown = ref(0);
  const codeHint = ref('获取验证码');
  const formState = ref({
    phoneOrEmail: '',
    code: '',
    sendType: 'login', 
    type: 0
  });

  const rules = {
    phoneOrEmail: [
      {
        type: 'string',
        required: true,
        message: '请您输入手机号码',
        trigger: ['blur', 'change'],
      },
      {
        validator: (rule, value) => {
          return uni.$u.test.mobile(value);
        },
        message: '手机号码不正确',
        trigger: ['change', 'blur'],
      },
    ],
  };

  function startCountdown() {
    countdown.value = 60;
    const timer = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value -= 1;

        codeHint.value = `${countdown.value}秒后重新发送`;
      } else {
        clearInterval(timer);
        codeHint.value = '获取验证码';
      }
    }, 1000);
  }

  const handleGetCode = () => {
    if (countdown.value === 0) {
      // 模拟向后端请求验证码
      uni.showLoading({
        title: '正在获取验证码',
      });

      sendCode(pick(formState.value, ['phoneOrEmail', 'sendType', 'type'])).then(() => {
        startCountdown();
        uni.hideLoading();
      });
    } else {
      uni.showToast({
        title: '倒计时结束后再发送'
      });
    }
  };

  function handleSubmit() {
    modifyPhone(omit(formState.value, ['sendType', 'type'])).then(({ data }) => {
      if(data.status === 200) {
        startCountdown();
        uni.hideLoading();
        userStore.getUserInfo().then(() => {
          uni.navigateBack()
        })
      }else {
        
      }
     
    });
    
  }

  return {
    formState,
    rules,
    countdown,
    codeHint,
    handleGetCode,
    handleSubmit,
  };
}

